package com.forest.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.forest.constants.EncryptionAlgorithm;
import com.forest.entity.SysAppInfo;
import com.forest.mapper.SysAppInfoMapper;
import com.forest.service.SysAppInfoService;
import com.forest.util.EncryptionKeyUtil;
import com.forest.util.EnvironmentHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class SysAppInfoServiceImpl extends ServiceImpl<SysAppInfoMapper, SysAppInfo> implements SysAppInfoService {

    @Override
    public SysAppInfo getByAppKey(String appKey) {
        QueryWrapper<SysAppInfo> ew = new QueryWrapper<>();
        ew.lambda().eq(SysAppInfo::getAppKey, appKey)
        .eq(SysAppInfo::getIsDelete, "010001")
        .eq(SysAppInfo::getStatus, "002001");
        List<SysAppInfo> appInfoList = this.list(ew);
        return appInfoList.size() > 0 ? appInfoList.get(0) : null;
    }


    @Override
    public String decryptKey(SysAppInfo appInfo) {
        int type = EncryptionAlgorithm.SM4.getAlgorithm().equals(StrUtil.isBlank(appInfo.getEncryptionAlgorithm()) ? EnvironmentHolder.getEncryptionAlgorithm() :appInfo.getEncryptionAlgorithm()) ? 1 : 2;
        String secretKey = StrUtil.equals(StrUtil.isBlank(appInfo.getEncryptionAlgorithm()) ? EnvironmentHolder.getEncryptionAlgorithm() : appInfo.getEncryptionAlgorithm(), EncryptionAlgorithm.SM4.getAlgorithm()) ? appInfo.getAppSecretSm4() : appInfo.getAppSecretAes();
        return EncryptionKeyUtil.getAppSecretKey(type,secretKey);
    }
}
